<template>
  <div class="bg">
    <!-- 顶部标题 -->
    <div class="top">
      <div class="title">发布采购</div>
      <div class="subheading">
        请尽量将采购产品的信息填写完整，方便卖家准确报价
      </div>
      <div class="line"></div>
    </div>

    <!-- 产品信息 -->
    <div class="productInformation">
      <div class="product">产品信息</div>
      <!-- <el-form ref="form" :model="form" label-width="80px"> -->
      <el-form label-width="80px" :disabled="!isEdit">
        <el-form-item label="选择分类">
          <el-select v-model="kind" placeholder="请选择分类">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购标题">
          <el-input
            placeholder="请输入采购标题，如采购ABS白色环保一级颗粒料"
            v-model="title"
            maxlength="25"
            show-word-limit
            @input="getInputValue"
          ></el-input>
        </el-form-item>
        <el-form-item label="采购数量">
          <el-input placeholder="请输入采购数量" v-model="number"></el-input>
        </el-form-item>
        <el-form-item label="意向价格">
          <el-input
            placeholder="请输入意向价格或电议"
            v-model="intentionPrice"
          ></el-input>
        </el-form-item>

        <el-form-item label="截止时间">
          <el-col :span="24">
            <el-date-picker
              type="date"
              placeholder="请选择采购截止时间"
              v-model="date1"
              style="width: 100%"
            ></el-date-picker>
          </el-col>
        </el-form-item>

        <el-form-item label="补充说明">
          <el-input
            type="textarea"
            v-model="desc"
            maxlength="50"
            show-word-limit
            @input="getDescValue"
            placeholder="（非必填选）请描述采购信息详细需求，如产品需求、环保、颜色冲击等……"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>

    <!-- 采购人信息 -->
    <div class="buyerInformation">
      <div class="buyer">采购人信息</div>
      <!-- <el-form ref="form" :model="form" label-width="80px"> -->
      <el-form label-width="80px" :disabled="!isEdit">
        <el-form-item label="公司名称">
          <el-input placeholder="请输入公司名称" v-model="company"></el-input>
        </el-form-item>

        <div class="people" v-for="(item, index) in peopleList" :key="index">
          <el-form-item label="姓名">
            <el-input placeholder="请输入姓名" v-model="item.name"></el-input>
          </el-form-item>
          <el-form-item label="职位">
            <el-input placeholder="请输入职位" v-model="item.job"></el-input>
          </el-form-item>
          <el-form-item label="手机号码">
            <el-input
              placeholder="请输入手机号码"
              v-model="item.phoneNumber"
            ></el-input>
          </el-form-item>
        </div>

        <el-form-item label="交货地">
          <el-cascader
            placeholder="请选择交货地"
            :options="addressList"
            :props="{ expandTrigger: 'hover', value: 'label' }"
            @change="handleChange"
            v-model="provinceCity"
          ></el-cascader>
        </el-form-item>
      </el-form>
    </div>

    <div class="button" v-if="isEdit">
      <el-button @click="$router.replace('./purchase_list')">取消</el-button>
      <el-button type="primary" @click="submit">确定发布</el-button>
    </div>
  </div>
</template>

<script>
import regionJson from "@/json/region";
import bus from "../../utils/bus.js";

export default {
  data() {
    return {
      address: "",
      province: "",
      city: "",
      title: "",
      kind: "",
      date1: "",
      desc: "",
      number: "",
      intentionPrice: "",
      company: "",
      peopleList: [{ name: "", job: "", phoneNumber: "" }],
      options: [
        { value: 0, label: "塑胶原料" },
        { value: 1, label: "改性塑料" },
        { value: 2, label: "再生塑料" },
        { value: 3, label: "破碎料" },
        { value: 4, label: "废塑料" },
      ],
      addressList: [],
      provinceCity: [],
      isEdit: true,
      defaultAddress: {},
      defaultLinkman: {},
      addressData: [],
    };
  },
  created() {
    this.addressList = regionJson;
    this.getLinkMan();
    this.infoMassage()
  },
  mounted() {
    bus.$on("updateCompanyName", (val) => {
      this.company = val;
    });
    bus.$on("updateName", (val) => {
      this.peopleList[0].name = val;
    });
    bus.$on("updatePosition", (val) => {
      this.peopleList[0].job = val;
    });
    bus.$on("updateMobile", (val) => {
      this.peopleList[0].phoneNumber = val;
    });
    bus.$on("updateDefaultProvince", (val) => {
      this.provinceCity = val;
      this.province = val;
    });
    bus.$on("updateDefaultCity", (val) => {
      this.provinceCity = val;
      this.city = val;
    });
  },

  methods: {
    // 获取采购联系人信息
    infoMassage() {
      this.$apiFun.getUserInfo().then(res => {
        this.company = res.result.supplierInformationCompanyName
        this.peopleList[0].name = res.result.supplierInformationLinkman
        this.peopleList[0].job = res.result.supplierInformationPosition
        this.peopleList[0].phoneNumber = res.result.supplierInformationMobile
      })
    },
    getLinkMan() {
      let mainLinkman = JSON.parse(sessionStorage.getItem("InfoLinkman"));
      this.defaultLinkman = mainLinkman;
      this.company = this.defaultLinkman.companyName;
      this.peopleList[0].name = this.defaultLinkman.name;
      this.peopleList[0].job = this.defaultLinkman.position;
      this.peopleList[0].phoneNumber = this.defaultLinkman.mobile;
    },

    // 详情接口
    async getPurchasingDetail(id) {
      let res = await this.$apiFun.getPurchasingDetail(id);
      console.log("res", res);
      // 数据回显
      this.company = res.result.companyName;
      this.date1 = res.result.deadlineTime;
      this.desc = res.result.productDescription;
      this.title = res.result.productName;
      this.name = res.result.name;
      this.job = res.result.position;
      this.phoneNumber = res.result.mobile;
      this.number = res.result.purchaseAmount;
      this.intentionPrice = res.result.intentionalPrice;
      this.province = res.result.deliverySiteProvince;
      this.city = res.result.city;
      this.provinceCity = [
        res.result.deliverySiteProvince,
        res.result.deliverySiteCity,
      ];
      if (res.result.purchasingLabel == 0) {
        this.kind = "塑胶原料";
      } else if (res.result.purchasingLabel == 1) {
        this.kind = "改性塑料";
      } else if (res.result.purchasingLabel == 2) {
        this.kind = "再生塑料";
      } else if (res.result.purchasingLabel == 3) {
        this.kind = "破碎料";
      } else if (res.result.purchasingLabel == 4) {
        this.kind = "废塑料";
      }
      this.peopleList[0].phoneNumber = res.result.mobile;
      this.peopleList[0].name = res.result.name;
      this.peopleList[0].job = res.result.position;
    },
    // 选择交货地
    handleChange(label) {
      this.province = label[0];
      this.city = label[1];
      this.provinceCity[0] = label[0];
      this.provinceCity[1] = label[1];
    },

    getInputValue(e) {
      // 清除对应的延时器
      clearTimeout(this.time);
      this.time = setTimeout(() => {
        // 当文字中间有连续两个空格时，只保留一个
        this.title = e.replace(/\s+/g, " ");
      }, 100);
    },
    getDescValue(e) {
      // 清除对应的延时器
      clearTimeout(this.time);
      this.time = setTimeout(() => {
        // 当文字中间有连续两个空格时，只保留一个
        this.desc = e.replace(/\s+/g, " ");
      }, 100);
    },

    // 提交发布
    async submit() {
      // if (this.kind == "") {
      //   console.log(111);
      // } else if (this.title == "") {
      //   console.log(222);
      // } else if (this.number == "") {
      //   console.log(333);
      // } else if (this.intentionPrice == "") {
      //   console.log(444);
      // } else if (this.date1 == "") {
      //   console.log(555);
      // } else if (this.peopleList[0].name == "") {
      //   console.log(666);
      // } else if (this.peopleList[0].phoneNumber == "") {
      //   console.log(777);
      // } else if (this.province == "") {
      //   console.log(888);
      // } else if (this.city == "") {
      //   console.log(999);
      // } else if (this.provinceCity[0] == undefined) {
      //   console.log(100);
      // } else if (this.provinceCity[1] == undefined) {
      //   console.log(1020);
      // }
      var reg_tel =
        /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
      if (
        this.kind == "" ||
        this.title == "" ||
        this.number == "" ||
        this.intentionPrice == "" ||
        this.date1 == "" ||
        this.peopleList[0].name == "" ||
        (this.province == "" && this.city == "") ||
        (this.provinceCity[0] == undefined && this.provinceCity[1] == undefined)
      ) {
        this.$message.error("当前信息未填写完整，请填写完后再提交");
      } else if (!reg_tel.test(this.peopleList[0].phoneNumber)) {
        this.$message.error("请填写正确的手机号码");
      } else {
        let params = {
          companyName: this.company,
          deadlineTime: this.date1, // 截止时间
          deliverySiteCity:
            this.city || this.defaultAddress.supplierInformationCity, // 市
          deliverySiteProvince:
            this.province || this.defaultAddress.supplierInformationProvince, // 省
          intentionalPrice: this.intentionPrice, // 意向价格,
          mobile: this.peopleList[0].phoneNumber,
          name: this.peopleList[0].name,
          position: this.peopleList[0].job,
          productDescription: this.desc,
          productName: this.title, // 产品名称或或标题
          purchaseAmount: this.number,
        };
        let res;
        if (this.kind == "塑胶原料") {
          params.purchasingLabel = 0;
        } else if (this.kind == "改性塑料") {
          params.purchasingLabel = 1;
        } else if (this.kind == "再生塑料") {
          params.purchasingLabel = 2;
        } else if (this.kind == "破碎料") {
          params.purchasingLabel = 3;
        } else if (this.kind == "废塑料") {
          params.purchasingLabel = 4;
        }
        if (this.$route.query.publishId) {
          params.id = this.$route.query.publishId;
          res = await this.$apiFun.updatePurchasing(params);
        } else {
          res = await this.$apiFun.addPurchasing(params);
        }
        if (res.code == 200) {
          this.$message({
            duration: 1500,
            message: "操作成功",
            type: "success",
          });
          this.$router.replace("./purchase_list");
        }
      }
    },
  },
  watch: {
    "$route.query.publishId": {
      handler(newName) {
        if (newName == undefined) {
          this.isEdit = true;
        }
        this.date1 = "";
        this.desc = "";
        this.title = "";
        this.name = "";
        this.job = "";
        this.phoneNumber = "";
        this.number = "";
        this.intentionPrice = "";
        this.kind = "";

        // this.company = "";
        // this.peopleList[0].phoneNumber = "";
        // this.peopleList[0].name = "";
        // this.peopleList[0].job = "";

        // this.provinceCity = [];

        if (newName) {
          this.getPurchasingDetail(newName);
          this.isEdit = this.$route.query.type == 1 ? false : true;
          console.log(this.isEdit);
        }
      },
      deep: true,
      immediate: true,
    },
  },
};
</script>

<style lang="less" scoped>
/deep/ .el-input,
/deep/ .el-textarea,
/deep/ .el-cascader {
  width: 100% !important;
  .el-input__count {
    background: transparent !important;
    bottom: 0 !important;
  }
}

/deep/ .el-button--default,
/deep/ .el-button--primary {
  width: 2rem;
  height: 0.4rem;
  line-height: 0.1rem;
  border-radius: 5px;
}

/deep/ .el-button--default {
  background: #ffffff;
  border: 1px solid #333333;
}

/deep/ .el-button--primary {
  background: #f42551;
  border: none;
  margin-left: 0.3rem;
}

// /deep/ .el-cascader-menu {
//   min-width: 1000px !important;
// }

/deep/ .el-select {
  width: 100% !important;
}

.bg {
  background: #ffffff;
  box-shadow: 0px 3px 20px 0px rgba(230, 230, 230, 0.8);
  border-radius: 10px;
  padding: 0.3rem 0.5rem;
  text-align: left;
  font-family: Microsoft YaHei;

  // 顶部标题
  .top {
    .title {
      font-size: 0.24rem;
      font-weight: bold;
      color: #333333;
      line-height: 0.3rem;
    }
    .subheading {
      font-size: 0.18rem;
      font-weight: 400;
      color: #666666;
      margin: 0.3rem 0;
    }
    .line {
      height: 2px;
      background: #efefef;
    }
  }

  // 产品信息、采购人信息
  .productInformation,
  .buyerInformation {
    margin-top: 0.3rem;
    width: 5.517rem;
    .product,
    .buyer {
      font-size: 0.2rem;
      font-weight: bold;
      color: #333333;
      line-height: 0.3rem;
      margin-bottom: 0.3rem;
    }
  }

  // 按钮
  .button {
    margin-top: 0.8rem;
    display: flex;
    justify-content: center;
  }
}
</style>